//
//  GHSettingViewController.m
//  GodHorses
//
//  Created by Mac on 2017/11/15.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "GHSettingViewController.h"
#import "UIViewController+STPresent.h"
#import "GHAddreeeMangeController.h"
#import "GHCardMangeViewController.h"
#import "GHAccountSafeViewController.h"
#import "GHSuggestViewController.h"
#import "GHLoginViewController.h"
#import "GHAboutUsViewController.h"
#import "GHCompanyDesViewController.h"
@interface GHSettingViewController ()
@property(nonatomic, strong) STButton                              *iconButton;
@property(nonatomic, strong) NSArray<NSArray*>                     *dataSouce;
@end

@implementation GHSettingViewController

#pragma mark --vc 生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    self.title = @"设置";
    [self configSubView];
    [self configDataSouce];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configSubView{
    self.iconButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 60, 60)
                                                title:nil
                                           titleColor:nil
                                            titleFont:0
                                         cornerRadius:30
                                      backgroundColor:nil
                                      backgroundImage:[UIImage imageNamed:@"3"]
                       
                                                image:nil];
    __weak typeof(self) weakSelf =  self;
    [self.iconButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedIconButton];
    }];
    [self.iconButton sd_setBackgroundImageWithURL:[NSURL URLWithString:self.userModel.face] forState:UIControlStateNormal];
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    footer.backgroundColor = self.tableView.backgroundColor;
    STButton * logoutButton = [[STButton alloc] initWithFrame:CGRectMake(30, 0, UIScreenWidth - 60, 44)
                                                        title:@"退出登录"
                                                   titleColor:GH_YellowBackGroundColor
                                                    titleFont:18
                                                 cornerRadius:5
                                              backgroundColor:GH_BlackBackGroundColor
                                              backgroundImage:nil
                                                        image:nil];
    [logoutButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedLogoutButton];
    }];
    logoutButton.st_centerY = 50;
    logoutButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [footer addSubview:logoutButton];
    self.tableView.tableFooterView = footer;
}
- (void)configDataSouce{
    
    NSArray * sectionOne = @[
                             [[GHTableEasyModel alloc] initWithTextString:@"头像" accessoryView:self.iconButton],
                             [[GHTableEasyModel alloc] initWithTextString:@"昵称" detailString:self.userModel.username],
                             [[GHTableEasyModel alloc] initWithTextString:@"姓名" detailString:self.userModel.name],
                             [[GHTableEasyModel alloc] initWithTextString:@"身份证号" detailString:self.userModel.id_card],
                             [[GHTableEasyModel alloc] initWithTextString:@"收货地址" detailString:@""]
                             ];
//    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];//获取项目版本号
//    version = [NSString stringWithFormat:@"v%@",version];
//    GHTableEasyModel * versionModel = [[GHTableEasyModel alloc] initWithTextString:@"当前版本" detailString:version];
//    versionModel.accessoryType = UITableViewCellAccessoryNone;
    NSArray * sectionTwo = @[
                             [[GHTableEasyModel alloc] initWithTextString:@"企业概况" detailString:@""],
                             [[GHTableEasyModel alloc] initWithTextString:@"联系我们" detailString:@""],
                             [[GHTableEasyModel alloc] initWithTextString:@"账号安全" detailString:@""],
                             //versionModel,
                             [[GHTableEasyModel alloc] initWithTextString:@"意见反馈" detailString:@""],
                             [[GHTableEasyModel alloc] initWithTextString:@"清除缓存" detailString:@"全部清除"]
                             
                             ];
    self.dataSouce = @[sectionOne,sectionTwo];
    [self.tableView reloadData];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count  ;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce[section].count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 70;
    }
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    cell.textLabel.textColor = UIColorFromRGBA(0x333333);
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.detailTextLabel.textColor = UIColorFromRGBA(0x999999);
    
    GHTableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
    cell.textLabel.text = model.textString;
    cell.detailTextLabel.text = model.detailString;
    if (model.accessoryView) {
        cell.accessoryView = model.accessoryView;
    }else{
        cell.accessoryType = model.accessoryType;
    }
    if (indexPath.section == 1 && indexPath.row == 4) {
        cell.detailTextLabel.textColor = GH_redColor;
    }else{
        cell.detailTextLabel.textColor = UIColorFromRGBA(0x999999);
    }
    
    
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    GHTableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
    //昵称
    if (indexPath.section == 0 && indexPath.row == 1) {
        [self onSelectedNameCellWithModel:model indexPath:indexPath];
    }
    //姓名
    if (indexPath.section == 0 && indexPath.row == 2) {
        [self onSelectedRealNameCellWithModel:model indexPath:indexPath];
    }
    //身份证
    if (indexPath.section == 0 && indexPath.row == 3) {
        [self onSelectedIDCardCellWithModel:model indexPath:indexPath];
    }
    
    //收货地址管理
    if (indexPath.section == 0 && indexPath.row == 4) {
        [self.navigationController pushViewController:[GHAddreeeMangeController new] animated:YES];
    }
    //银行卡
//    if (indexPath.section == 0 && indexPath.row == 4) {
//        [self.navigationController pushViewController:[GHCardMangeViewController new] animated:YES];
//    }
    //企业概况
    if (indexPath.section == 1 && indexPath.row == 0) {
        [self.navigationController pushViewController:[GHCompanyDesViewController new] animated:YES];
    }
    //联系我们
    if (indexPath.section == 1 && indexPath.row == 1) {
        [self.navigationController pushViewController:[GHAboutUsViewController new] animated:YES];
    }
    //账号安全
    if (indexPath.section == 1 && indexPath.row == 2) {
        GHAccountSafeViewController * vc =  [GHAccountSafeViewController new];
        vc.userModel = self.userModel;
        [self.navigationController pushViewController:vc animated:YES];
    }
    //意见反馈
    if (indexPath.section == 1 && indexPath.row == 3) {
        [self.navigationController pushViewController:[GHSuggestViewController new] animated:YES];
    }
    if (indexPath.section == 1 && indexPath.row == 4) {
        [self onSelectedClearCellWithModel:model];
    }
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --Action Method
- (void)onSelectedIconButton{
    __weak typeof(self) weakSelf =  self;
    [self showDefultImagePicker:^(UIImage *image) {
        [weakSelf sendIconChangeRequestWithImage:image];
    }];
}

//昵称
- (void)onSelectedNameCellWithModel:(GHTableEasyModel*)model indexPath:(NSIndexPath*)indexPath{
    
    STTableViewDetailController * detail =
    [[STTableViewDetailController alloc] initWithPlaceholder:@"请输入昵称"
                                                       title:@"昵称"
                                                        text:model.detailString
                                                      handle:^(NSString *text) {
                                                          if (text.length && ![text isEqualToString:model.detailString]) {
                                                              [self sendInfoChangeRequestWithName:text indexPath:indexPath];
                                                          }
                                                          if (!text.length) {
                                                              [SVProgressHUD showErrorWithStatus:@"昵称不能为空"];
                                                          }
                                                          [self.navigationController popViewControllerAnimated:YES];
                                                      }];
    detail.detailLabel.text = @"";
    detail.isShowTextNum = NO;
    [self.navigationController pushViewController:detail animated:YES];
}
//真实姓名
- (void)onSelectedRealNameCellWithModel:(GHTableEasyModel*)model indexPath:(NSIndexPath*)indexPath{
    
    STTableViewDetailController * detail =
    [[STTableViewDetailController alloc] initWithPlaceholder:@"请输入姓名"
                                                       title:@"姓名"
                                                        text:model.detailString
                                                      handle:^(NSString *text) {
                                                          if (text.length && ![text isEqualToString:model.detailString]) {
                                                              [self sendInfoChangeRequestWithRealName:text indexPath:indexPath];
                                                          }
                                                          if (!text.length) {
                                                              [SVProgressHUD showErrorWithStatus:@"姓名不能为空"];
                                                          }
                                                          [self.navigationController popViewControllerAnimated:YES];
                                                      }];
    detail.detailLabel.text = @"";
    detail.isShowTextNum = NO;
    [self.navigationController pushViewController:detail animated:YES];
}
//身份证
- (void)onSelectedIDCardCellWithModel:(GHTableEasyModel*)model indexPath:(NSIndexPath*)indexPath{
    STTableViewDetailController * detail =
    [[STTableViewDetailController alloc] initWithPlaceholder:@"请输入身份证号"
                                                       title:@"身份证号码"
                                                        text:model.detailString
                                                      handle:^(NSString *text) {
                                                          if (text.length && ![text isEqualToString:model.detailString]) {
                                                              [self sendInfoChangeRequestWithIdCard:text indexPath:indexPath];
                                                          }
                                                          if (!text.length) {
                                                              [SVProgressHUD showErrorWithStatus:@"身份证号码不能为空"];
                                                          }
                                                          [self.navigationController popViewControllerAnimated:YES];
                                                      }];
    detail.detailLabel.text = @"请务必填写自己真实有效的身份证信息";
    detail.isShowTextNum = NO;
    detail.textFiled.keyboardType = UIKeyboardTypeASCIICapable;
    [self.navigationController pushViewController:detail animated:YES];
}
//银行卡
//清除缓存
- (void)onSelectedClearCellWithModel:(GHTableEasyModel*)model{
    
    [self showAlertCancelAndConfirm:@"确定要清除所有缓存?" andWithBlock:^(NSString *name) {
        if ([name isEqualToString:@"确认"]) {
            [[SDImageCache sharedImageCache] clearDisk];
            [[SDImageCache sharedImageCache] clearMemory];
            [SVProgressHUD showSuccessWithStatus:@"清除成功"];
        }
    }];
    
}
//退出登录
- (void)onSelectedLogoutButton{
    [self showAlertTitle:@"请注意"
                 message:@"确定要退出登录吗？"
               leftTitle:@"取消"
              rightTitle:@"确认"
                   block:^(NSString *name) {
                       if ([name isEqualToString:@"确认"]) {
                           [[GHUserManger defult] removeUserPreferce];
                           [UIApplication sharedApplication].keyWindow.rootViewController = [[STNavigationController alloc] initWithRootViewController:[GHLoginViewController new]];
                       }
                   }];
    
}
#pragma mark --Private Method
- (NSDictionary*)nameDicWithNameValue:(NSString*)name{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    [dic setObject:@"1" forKey:@"type"];
    if (name.length) {
        [dic setObject:name forKey:@"username"];
    }
    return dic;
}
- (NSDictionary*)dicWithIDCradValue:(NSString*)idCard{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    [dic setObject:@"2" forKey:@"type"];
    if (idCard.length) {
        [dic setObject:idCard forKey:@"id_card"];
    }
    return dic;
}
#pragma mark --NetWork Method
- (void)sendIconChangeRequestWithImage:(UIImage*)image{
    [SVProgressHUD showWithStatus:@"正在更换头像，请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    [dic setObject:@"3" forKey:@"type"];
    [[STNetWrokManger defaultClient] imageRequestWithPath:@"http://test.smqyp.com/Api/system/edit_personal"
                                               parameters:dic
                                                    image:image
                                                 progress:^(NSProgress *progress) {
                                                     
                                                 } success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                     [SVProgressHUD dismiss];
                                                     [self.iconButton setBackgroundImage:image forState:UIControlStateNormal];
                                                     [SVProgressHUD showSuccessWithStatus:@"更换图片成功"];
                                                 } failure:^(NSString *stateCode, STError *error) {
                                                     [SVProgressHUD dismiss];
                                                     [SVProgressHUD showErrorWithStatus:error.desc];
                                                     
                                                 }];
    
}
- (void)sendInfoChangeRequestWithName:(NSString*)name indexPath:(NSIndexPath*)indexPath{
    NSDictionary * dic = [self nameDicWithNameValue:name];
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/system/edit_personal"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD showSuccessWithStatus:@"更改昵称成功"];
                                                 GHTableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
                                                 model.detailString = name;
                                                 [self.tableView reloadData];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendInfoChangeRequestWithRealName:(NSString*)name indexPath:(NSIndexPath*)indexPath{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    [dic setObject:@"4" forKey:@"type"];
    if (name.length) {
        [dic setObject:name forKey:@"name"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/system/edit_personal"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD showSuccessWithStatus:@"更改姓名成功"];
                                                 GHTableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
                                                 model.detailString = name;
                                                 [self.tableView reloadData];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendInfoChangeRequestWithIdCard:(NSString*)idCard indexPath:(NSIndexPath*)indexPath{
    NSDictionary * dic = [self dicWithIDCradValue:idCard];
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/system/edit_personal"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD showSuccessWithStatus:@"更改昵称成功"];
                                                 GHTableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
                                                 model.detailString = idCard;
                                                 [self.tableView reloadData];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end

